from datetime import datetime
from django.contrib import admin, messages

from interview.models import Candidate
from jobs.models import Job, Resume


class JobManager(admin.ModelAdmin):
    # 添加数据时隐藏的字段
    exclude = ["creator", "created_at", "updated_at"]
    # 展示字段
    list_display = ["job_name", "job_type", "job_city", "creator", "created_at", "updated_at"]

    def save_model(self, request, obj, form, change):
        """
        数据保存前会掉用此方法
        :param request:
        :param obj:
        :param form:
        :param change:
        :return:
        """
        # 由于在添加数据时将创建人隐藏了，所以这块在保存数据库时指定为当前登录用户
        obj.creator = request.user
        super().save_model(request, obj, form, change)


def enter_interviewer_process(modeladmin, request, queryset):
    candidate_names = ""
    for resume in queryset:
        candidate = Candidate()
        candidate.__dict__.update(resume.__dict__)
        candidate.created_at = datetime.now()
        candidate.updated_at = datetime.now()
        candidate_names = candidate.username + ',' + candidate_names
        candidate.creator = request.user.username
        candidate.save()
    messages.add_message(request, messages.INFO, "候选人：%s 已成功进入面试流程" % (candidate_names))


enter_interviewer_process.short_description = u"进入面试流程"


class ResumeAdmin(admin.ModelAdmin):

    actions = (enter_interviewer_process,)

    list_display = ('username', 'applicant', 'city', 'apply_position', 'bachelor_school',
                    'master_school', 'major', 'created_at')
    readonly_fields = ('applicant', 'created_at', 'updated_at')

    fieldsets = (
        (None, {'fields': (
            "applicant", ("username", "city", "phone"),
            ("email", "apply_position", "born_address", "gender"),
            ("bachelor_school", "master_school"), ("major", "degree"), ("created_at", "updated_at"),
            "candidate_introduction", "work_experience", "project_experience")}),
    )

    def save_model(self, request, obj, form, change):
        obj.applicant = request.user
        super().save_model(request, obj, form, change)


class ResumeAdmin(admin.ModelAdmin):
    list_display = ('username', 'applicant', 'city', 'apply_position', 'bachelor_school',
                    'master_school', 'major', 'created_at')
    readonly_fields = ('applicant', 'created_at', 'updated_at')

    fieldsets = (
        (None, {'fields': (
            "applicant", ("username", "city", "phone"),
            ("email", "apply_position", "born_address", "gender"),
            ("bachelor_school", "master_school"), ("major", "degree"), ("created_at", "updated_at"),
            "candidate_introduction", "work_experience", "project_experience")}),
    )

    def save_model(self, request, obj, form, change):
        obj.applicant = request.user
        super().save_model(request, obj, form, change)


admin.site.register(Job, JobManager)
admin.site.register(Resume, ResumeAdmin)
